<?php
/***
 * 用户模块后台控制器
 *
 *
 * @author    wangmx <wangmx@yunys.com.cn>
 * @copyright 2016 QuanZhouYunYiShang Inc.
 */

namespace App\Http\Controllers\Backstage;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Response;
use App\Services\UserService\UserBackstage;
use App\Services\ProductsService\ProductTool;


class UserController extends BaseController
{

    protected $UserBack;
    protected $ProductsService;


    public function __construct(UserBackstage $UserBack,ProductTool $Product)
    {
        $this->UserBack = $UserBack;
        $this->Product = $Product;

    }

    /**
     * 用户列表
     */
    public function user_list(Request $request){
        $lists = $this->UserBack->userList($request);
        return view('backstage.user.userlist')->with('users', $lists);
    }

    public function search(Request $request){
        $phone = $request->get('phone');
        $lists = DB::table('users')->orderBy('created_at', 'desc')
            ->where('phone', 'like', '%' . $phone . '%')
            ->distinct()
            ->paginate(10);
        return view('backstage.user.userlist')->with('users', $lists);
    }
    
    public function createUser(Request $request){
        $phone = trim($request->get('phone'));
        $info = DB::table('users')->where('phone', $phone)->first();
        if ($info == null) {
            $udid = $request->get('udid', '');
            $nick_name = substr_replace($phone, '****', 3, 4);
            $avatar = 'Default_avatar.png';
            $original_avatar = 'original_Default_avatar.png';
            $cover_map = 'default_cover_map.png';
            DB::table('users')->insert(
                [
                    'phone' => $phone,
                    'nick_name' => $nick_name,
                    'avatar' => $avatar,
                    'original_avatar' => $original_avatar,
                    'gender' => 0,
                    'birthday' => 0,
                    'area' => '',
                    'user_type' => 0,
                    'login_type' => 0,
                    'udid' => $udid,
                    'cover_map' => $cover_map,
                    'udid_record_time' => time(),
                    'token' => '',
                    'token_record_time' => time(),
                    'created_at' => time(),
                    'updated_at' => time(),
                ]
            );
            $user_id = DB::table('users')->where('phone', $phone)->value('user_id');
            $this->Product->createDefaultCollections($user_id); //创建默认作品集
        }
        $user_id = DB::table('users')->where('phone', $phone)->value('user_id');
        $result = array('message' => '成功', 'result' => $user_id, 'state' => 'M00000');
        return Response::json($result);
    }
}
